import JSEncrypt from 'jsencrypt'
const encrypt = new JSEncrypt();
var publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCeCDcnFrS7DIRbvZLHreVUzaMbAFy2DYmioxBK606urY4rVR8IgLgUhnyw2/GQ99pyr8lGtqPeOoapantw1XwEVyi74MDxs4UDL8j4OZR1Es7HVGOB0GwKWobdU9cm/1iDwGyouSmijxKyAePg6KsLNgbjDPYZRS11bYEuZ8/RLQIDAQAB';
encrypt.setPublicKey('-----BEGIN PUBLIC KEY-----' + publicKey + '-----END PUBLIC KEY-----')

const random = (length) => {
  var str = Math.random().toString(36).substr(2);
  if (str.length>=length) {
    return str.substr(0, length);
  }
  str += random(length-str.length);
  return str;
}

export const rsaEncode = (src)=>{
  let data = encrypt.encrypt(src); // 加密
  return data
};

export const getKey = ()=>{
  let key = { key: random(16), iv: random(16) }; // 生成密钥
  let code = rsaEncode(key.key + ',' + key.iv) // 给密钥加密,在将加密后的密钥传给后端
  window.codeArr = window.codeArr || {}
  codeArr[code] = key
  return {
    key, code
  }
};

export const getAesKey = (aes)=>{
  let key = JSON.parse(JSON.stringify(codeArr[aes]))
  delete codeArr[aes]
  return key
};



window.getKey = getKey
window.rsaEncode = rsaEncode
